/*
 * @Author: 千锋爱佛僧
 * @公众号: 大前端私房菜
 * @Slogan: 千锋精品教程，好学得不像实力派！
 */
/*
 * @Author: 千锋爱佛僧
 * @公众号: 大前端私房菜
 * @Slogan: 千锋精品教程，好学得不像实力派！
 */
import React, { useEffect, useState } from "react";
import { Button, Image, Space, Table, Tag } from "antd";
import type { ColumnsType } from "antd/es/table";
import { CategoryType } from "@/types/pro";
import { categoryGet } from "@/api/pro";
import { useNavigate } from "react-router-dom";
import qs from "query-string";
import Auth from "@/guard/Auth";

// const data: CategoryType[] = [
//   {
//     objectId: "sss",
//     level: 1,
//     name: "开发",
//     icon: "img.png",
//     parent_id: "123",
//     grandparent_id: "456",
//   },
// ];
// 将数据包处理为tree格式
function processData(data: CategoryType[]) {
  const root: any = {};
  for (const item of data.sort((a, b) => a.level - b.level)) {
    const parent =
      (item.parent_id && root[item.parent_id]) ||
      (item.grandparent_id && root[item.grandparent_id]) ||
      root;
    parent.children = parent.children || [];
    parent.children.push(item);
    root[item.objectId] = item;
  }
  console.log(root);
  return root.children;
}
const CateList: React.FC = () => {
  let [data, setData] = useState<CategoryType[]>([]);
  const navigate = useNavigate();
  const columns: ColumnsType<CategoryType> = [
    {
      title: "类目层级",
      dataIndex: "level",
      key: "level",
      render: (level, record, index) => {
        let lvArr = ["", "一级类目", "二级类目", "三级类目"];
        return lvArr[level];
      },
    },
    {
      title: "分类名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "分类icon",
      dataIndex: "icon",
      key: "icon",
      render: (url, record) => {
        return record.level == 1 ? <Image src={url} width={50} /> : "-";
      },
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            size="small"
            onClick={() => {
              handleEdit(record);
            }}
          >
            编辑
          </Button>
          <Auth>
            <Button type="primary" size="small" danger>
              删除
            </Button>
          </Auth>
        </Space>
      ),
    },
  ];
  const handleEdit = (record: CategoryType) => {
    delete record.children;
    // console.log(record);
    let query = qs.stringify(record);
    navigate(`/category/edit?${query}`);
  };
  useEffect(() => {
    categoryGet().then((res) => {
      let result = processData(res.data.results);
      console.log(result);
      setData(result);
    });
  }, []);
  return <Table columns={columns} dataSource={data} rowKey="objectId" />;
};

export default CateList;
